package com.snxun.browser_light.adapter.home;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.snxun.browser_light.bean.AppInfoBean;
import com.snxun.browser_light.module.home.WebViewFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 主界面viewpager适配器
 * Created by Yangjw on 2020/11/20.
 */
public class MainViewPagerAdapeter extends FragmentStatePagerAdapter {

    /**
     * WebviewFragment界面APP列表的数据
     */
    private List<WebViewFragment> mFragments = new ArrayList<>();

    public MainViewPagerAdapeter(@NonNull FragmentManager fm) {
        super(fm);
    }

    private boolean mIsAdd;

    /**
     * 新增一个新的fragment
     * @param newFragment 新创建的fragment
     */
    public void addData(WebViewFragment newFragment) {
        mIsAdd = true;
        mFragments.add(newFragment);
        notifyDataSetChanged();
    }

    /**
     * 清空所有fragment，并创建一个新的fragment
     *
     * @param newFragment 新创建的fragment
     */
    public void clearDataAndCreateNewFragment(WebViewFragment newFragment) {
        mIsAdd = false;
        mFragments.clear();
        mFragments.add(newFragment);
        notifyDataSetChanged();
    }

    /**
     * 删除当个fragment
     *
     * @param tag   需要删除fragment对应的tag
     * @param mList 用于删除最后一页时，新增一个默认页面
     */
    public void deleteSingleFragment(String tag, List<AppInfoBean> mList) {
        mIsAdd = false;
        if (mFragments.size() == 1) {
            mFragments.add(WebViewFragment.newInstance(mList, String.valueOf(UUID.randomUUID())));
        }
        for (WebViewFragment fragment : mFragments) {
            if (fragment.getFragmentTag().equals(tag)) {
                mFragments.remove(fragment);
                break;
            }
        }
        notifyDataSetChanged();

    }


    @NonNull
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        if (mIsAdd)
            return POSITION_UNCHANGED;
        else
            return POSITION_NONE;
    }


    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.destroyItem(container, position, object);

    }
}
